﻿using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Playables;

public class PlayableController : MonoBehaviour
{
    public PlayableDirector Director;

    public InputField TimeField;
    public Button GoButton;

    //public event Action<PlayableDirector> played;
    //public event Action<PlayableDirector> paused;
    //public event Action<PlayableDirector> stopped;

    void OnPlayed(PlayableDirector director)
    {
        //Debug.Log("OnPlayed: " + Director.state);
    }

    void OnPaused(PlayableDirector director)
    {
        //Debug.Log("OnPaused: " + Director.state);
    }

    void OnStoped(PlayableDirector director)
    {
        //Debug.Log("OnStoped: " + Director.state);
    }

    double timeBeforeStop = 0;
    public void OnStopButton()
    {
        TimeField.text = "0";

        timeBeforeStop = Director.time;

        OnGoButton(true);
    }

    private void Start()
    {
        //Debug.Log("Start: " + Director.state);

        Director.played += OnPlayed;
        Director.paused += OnPaused;
        Director.stopped += OnStoped;

        GoButton.onClick.AddListener( () => { OnGoButton(false); });
    }

    private void OnGoButton(bool useRememberTime)
    {
        Director.Pause();

        double originTime = 0;
        if (useRememberTime)
        {
            originTime = timeBeforeStop;
        }
        else
        {
            originTime = Director.time;
        }
        double destinationTime = double.Parse(TimeField.text);
        
        //Debug.Log(originTime);  //stop 以后，不管时间线停止哪，获取的原始时间都是为0
        //                        //所以必须在stop前，记住时间
        //Debug.Log(destinationTime);

        Director.time = destinationTime;
        Director.Evaluate();

        JumpabelManager.OnDirectorJump(Director, originTime, destinationTime);

        //Director.Play();
    }
}
